import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

import { Node } from '@antv/x6';
import { uuid } from '@antv/x6/lib/util/string/uuid';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AddPortModalComponent } from '../add-port-modal/add-port-modal.component';
import { WFButton } from '../type';

import { distinctUntilChanged, debounceTime } from 'rxjs/operators';
import { TypeFrom } from 'src/app/component/basic';
import { GraphService } from 'src/app/util/graph.service';

@Component({
  selector: 'wf-node-set',
  templateUrl: './node-set.component.html',
  styleUrls: ['./node-set.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class NodeSetComponent implements OnInit, OnChanges {
  stepName!: string | null;

  portData: any = [];
  form!: FormGroup;

  @Input() currentNode: Node<Node.Properties> | undefined;
  @Input() text!: string;

  get formArray() {
    return (this.form.get('btnArray') as FormArray).controls as FormGroup[];
  }

  constructor(
    private fb: FormBuilder,
    private modal: NzModalService,
    private cd: ChangeDetectorRef,
    private graphService: GraphService
  ) { }


  ngOnInit(): void {
    this.init();
    this.graphService.addPort$.subscribe(() => {
      this.getPorts();
    });
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.currentNode && !changes.currentNode.isFirstChange()) {
      console.log('change:::', changes);
      this.init();
    }
  }

  addBtn() {
    const sort = 1;
    (this.form.get('btnArray') as FormArray).push(this.fb.group({
      id: uuid(),
      value: `按钮${sort}`,
      sort,
      allot: false,
      from: TypeFrom.Button
    }));
  }

  deleteBtn(i: number) {
    (this.form.get('btnArray') as FormArray).removeAt(i);
  }

  addPort() {
    const modalInstance = this.modal.create({
      nzTitle: '添加链接桩',
      nzContent: AddPortModalComponent,
      nzMaskClosable: false,
      nzFooter: null,
      nzWidth: '35%',
    });
    modalInstance.afterClose.subscribe(res => {
      if (res) {
        this.currentNode!.addPort({
          group: 'out',
          attrs: {
            text: { text: res.name },
          },
        });
        this.getPorts();
      }
    });
  }

  editPort(item: any) {
    const modalInstance = this.modal.create({
      nzTitle: '编辑链接桩',
      nzContent: AddPortModalComponent,
      nzMaskClosable: false,
      nzFooter: null,
      nzWidth: '35%',
      nzComponentParams: {
        item
      }
    });
    modalInstance.afterClose.subscribe(res => {
      if (res) {
        if (this.currentNode!.hasPort(res.id)) {
          this.currentNode!.setPortProp(res.id, 'attrs/text/text', res.name);
          this.getPorts();
        }
      }
    });
  }

  removePort(item: any) {
    this.currentNode!.removePort(item.id);
    this.getPorts();
  }


  getPorts() {
    const ports = this.currentNode!.getPorts();
    this.portData = ports.map(item => {
      return {
        id: item.id,
        group: 'out',
        name: item.attrs?.text.text
      };
    });
    this.cd.markForCheck();
  }

  private init() {
    this.form = this.fb.group({
      btnArray: this.fb.array([])
    });
    const btnList: WFButton[] = this.currentNode!.getData().btnList;
    btnList.forEach((btn) => {
      const form = this.fb.group({
        id: [],
        sort: [],
        value: [],
        allot: [false],
        from: [TypeFrom.Button]
      });
      form.patchValue(btn);
      (this.form.get('btnArray') as FormArray).push(form);
    });
    this.getPorts();

    this.form.get('btnArray')?.valueChanges.pipe(distinctUntilChanged(), debounceTime(500)).subscribe(value => {
      this.currentNode?.updateData({ btnList: value });
    });
  }
}
